package com.tfswx.ruleengine.fn;

import cn.hutool.core.date.DateUtil;
import com.greenpineyu.fel.context.FelContext;
import com.tfswx.ruleengine.compute.exception.AppException;
import com.tfswx.ruleengine.compute.gzjy.BaseFn;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class DifferYMD extends BaseFn {

    @Override
    public Object call(Object[] arguments, FelContext context) {
        String dateStr1 = (String) arguments[0];
        String dateStr2 = (String) arguments[1];
        if (StringUtils.isBlank(dateStr1) || StringUtils.isBlank(dateStr2)) {
            return "";
        } else {
            LocalDate startDate = DateUtil.parse(dateStr1).toSqlDate().toLocalDate();
            LocalDate endDate = DateUtil.parse(dateStr2).toSqlDate().toLocalDate();
            StringBuilder sb = new StringBuilder();
            if (endDate.isAfter(startDate)) {
                int differY = endDate.getYear() - startDate.getYear();
                int differM = endDate.getMonthValue() - startDate.getMonthValue();
                if (differY > 0) {
                    if (differM > 0) {
                        sb.append(differY).append("年").append(differM).append("月");
                    } else if (differM == 0) {
                        sb.append(differY).append("年");
                    } else {
                        sb.append(differY - 1).append("年").append(differM + 12).append("月");
                    }
                } else {
                    sb.append(differM).append("月");
                }
                return sb.toString();
            } else {
                throw new AppException("endDate必须在startDate之后");
            }
        }
    }

    @Override
    public String getZwmc() {
        return "日期相差月份";
    }


    @Override
    public List<Param> getParams() {
        List<Param> params = new ArrayList<>();
        params.add(new Param("startDate"));
        params.add(new Param("endDate"));
        return params;
    }

    @Override
    public String getName() {
        return "differYMD";
    }
}
